import json
from .paper import OpenReviewPaper
from meta_service.tistore import TopicHandle

def LoadPaperFromTisHandle(topic_handle:TopicHandle,limit:int=0):
    """
    加载当前Handle下的所有论文<br>
    如果论文数量较多, 请谨慎使用!
    """
    paper_list = []
    if isinstance(topic_handle,TopicHandle):
        index_list = topic_handle.GetIndexList()
        if limit <= 0:
            limit = len(index_list)
        for idx in range(limit):
            filename = index_list[idx]
            index_handle = topic_handle.GetIndexHandle(filename)
            file_path = index_handle.GetIndexPath()
            paper = None
            try:
                with open(file_path,"r",encoding="utf-8") as fp:
                    data = json.load(fp)
                paper = OpenReviewPaper().from_json(data)
            except Exception as e:
                print(f"error when load paper: {str(e)}")
                paper = None
            # 判断
            if paper is None:
                continue
            paper_list.append(paper)
    return paper_list


def CountPaperInTisHandle(topic_handle:TopicHandle):
    """
    获取当前Handle下论文的数量
    """
    lenth = 0
    if isinstance(topic_handle,TopicHandle):
        index_list = topic_handle.GetIndexList()
        lenth = len(index_list)
    return lenth


def LoadPaperFromTisHandleAtIdx(topic_handle:TopicHandle,idx:int):
    """
    加载当前Handle下指定位置的论文
    """
    if isinstance(topic_handle,TopicHandle):
        index_list = topic_handle.GetIndexList()
        lenth = len(index_list)
        if idx < 0 or idx >= lenth:
            print(f"idx:{idx} is out of range that length: {lenth}")
            return None
        filename = index_list[idx]
        index_handle = topic_handle.GetIndexHandle(filename)
        file_path = index_handle.GetIndexPath()
        paper = None
        try:
            with open(file_path,"r",encoding="utf-8") as fp:
                data = json.load(fp)
            paper = OpenReviewPaper().from_json(data)
        except Exception as e:
            print(f"error when load paper: {str(e)}")
            paper = None
        return paper

